package sk.openit.xml.stax.iterator;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;

import sk.openit.xml.entity.DbConfig;
import sk.openit.xml.entity.DbConfigTags;

public class DbConfigReader implements DbConfigTags {
	private DbConfig dbConfig;
    private String fileName = "database-config.xml";
	
	public DbConfigReader(String fileName) {
		this.fileName = fileName;
	}
	
    public void process() {
		XMLInputFactory factory = XMLInputFactory.newInstance();

		try {
			XMLEventReader r = factory.createXMLEventReader(fileName, new FileInputStream(fileName));
			dbConfig = new DbConfig();
			while (r.hasNext()) {
				XMLEvent e = r.nextEvent();
				if (e.isStartElement()) {
					processTag(e, r);
				}
			}
		} catch (FileNotFoundException e) {
			System.err.println("Unable to find file: " + fileName);
			e.printStackTrace();
		} catch (XMLStreamException e) {
			System.err.println("Unable to process xml stream");
			e.printStackTrace();
		}
    }

    
    private void processTag(XMLEvent event, XMLEventReader xmlEventReader) {    	
    	String tagName = event.asStartElement().getName().toString();
		try {
			XMLEvent nextEvent = xmlEventReader.peek();	    	
			
	    	if (CONFIG.equals(tagName)) {
	    		dbConfig.setDbType(event.asStartElement().getAttributeByName(new QName(DB_TYPE)).getValue());    		
	    	} else if (HOST.equals(tagName)) {
				dbConfig.setHost(nextEvent.asCharacters().getData());
	    	} else if (PORT.equals(tagName)) {
				dbConfig.setPort(nextEvent.asCharacters().getData());    	
	    	} else if (INSTANCE.equals(tagName)) {
				dbConfig.setInstance(nextEvent.asCharacters().getData());    	
	    	} else if (DATABASE.equals(tagName)) {
				dbConfig.setDatabase(nextEvent.asCharacters().getData());    	
	    	} else if (USER.equals(tagName)) {
				dbConfig.setUser(nextEvent.asCharacters().getData());    	
	    	}
		} catch (XMLStreamException e) {
			System.err.println("Unable to process tag: " + tagName);
			e.printStackTrace();
		}    	
	}

	public DbConfig getDbConfig() {
		return dbConfig;
	}
}
